<?php


namespace app\api\controller\course\order;


use app\api\controller\Controller;
use app\api\model\user\BalanceLog;
use app\api\model\UserCoupon as UserCouponModel;
use app\api\service\Payment;
use app\common\enum\order\PayType;
use app\common\enum\OrderType;
use app\common\enum\user\balanceLog\Scene;
use app\common\exception\BaseException;
use app\common\library\helper;
use app\common\model\CourseCard;
use app\common\model\CourseOrder;
use app\common\model\video\Course;
use app\common\model\video\UserCourse;
use think\Db;
use think\Hook;

class Order extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->user = $this->getUser();   // 用户信息
        Hook::listen('course');
    }

    public function CardDetail(){
        $param = request()->param('card_id');
        //会员卡列表
        $CardInfo = CourseCard::detail($param);
        $CardInfo['file_name'] = $CardInfo['image'][0]['file_path'];
        //优惠券
        $Coupon = UserCouponModel::getUserCouponList($this->user['user_id'],$CardInfo['price']);
        return $this->renderSuccess([
            'CardInfo' => $CardInfo,  // 会员卡详情
            'Coupon'=>array_values($Coupon)
        ]);
    }

    public function CourseOrder(){
        if ($this->request->isPost()){
            if ($this->user['phone'] == ''){
                return $this->renderError('还未绑定手机号');
            }
            $data = $this->request->param();
            if (!isset($data['card_id']) || $data['card_id'] == ''){
                return $this->renderError('请选择购买的课程卡');
            }
            $courseCard = CourseCard::detail($data['card_id']);
            if (!$courseCard || $courseCard['is_delete'] == 1){
                return $this->renderError('课程卡不存在');
            }
            if ($courseCard['status'] == 20){
                return $this->renderError('课程卡已下架');
            }
            $pay_money = $courseCard['price'];
            $coupon_money = 0;
            $coupon_id = 0;
            if(isset($data['coupon_id']) && $data['coupon_id'] > 0){
                //可用优惠券
                $couponList = UserCouponModel::getUserCouponList($this->user['user_id'],$pay_money);
                // 获取优惠券信息
                $couponInfo = helper::getArrayItemByColumn($couponList, 'user_coupon_id', $data['coupon_id']);
                if ($couponInfo == false) {
                    return $this->renderError('未找到优惠券信息');
                }
                $pay_money = $pay_money - $couponInfo['reduced_price'];
                $coupon_id = $data['coupon_id'];
                $coupon_money = $couponInfo['reduced_price'];
            }
            $pay_type = PayType::WECHAT;
            if ($pay_type == 10){
                //检查余额是否足够
                if ($this->user['balance'] < $pay_money){
                    return $this->renderError('账户余额不足');
                }
            }

            $image = Db::name('course_card_image')->where(['course_card_id'=>$courseCard['id']])->order('id asc')->find();
            $Add['order_no'] = date('YmdHis').randNumber(6);
            $Add['total_price'] = $courseCard['price'];
            $Add['order_price'] = $pay_money;
            $Add['pay_price'] = $pay_money;
            $Add['type'] = $courseCard['type'];//1次卡2团课
            $Add['pay_type'] = 10;
//            $Add['pay_status'] = 20;
            $Add['create_time'] = time();
            $Add['order_status'] = 10;//订单状态
            $Add['shop_id'] = $courseCard['shop_id'];
            $Add['user_id'] = $this->user['user_id'];//小程序id
            $Add['wxapp_id'] = $this->user['wxapp_id'];//小程序id
            $Add['coupon_id'] = $coupon_id;//优惠券
            $Add['coupon_money'] = $coupon_money; //优惠金额
            //卡具体信息
            $Detail['course_card_id'] = $courseCard['id'];
            $Detail['goods_name'] = $courseCard['goods_name'];
            $Detail['image_id'] = $image['image_id'];
            $Detail['content'] = $courseCard['content'];
            $Detail['nums'] = $courseCard['nums'];
            $Detail['remain_nums'] = $courseCard['nums'];
            $Detail['days'] = $courseCard['days'];
            $Detail['total_num'] = 1;
            $Detail['total_price'] = $pay_money;
            $Detail['order_id'] = '';
            $Detail['type'] = $courseCard['type']; //1次卡2团课
            $Detail['user_id'] = $this->user['user_id'];
            $Detail['shop_id'] = $courseCard['shop_id'];
            $Detail['wxapp_id'] = $this->user['wxapp_id'];
            $Detail['create_time'] = time();
            if ($pay_type == 10){
                //插入数据
                Db::startTrans();
                try {
                    $Add['is_active'] = 1;//激活
                    $order_id = Db::name('course_order')->insertGetId($Add);
                    $Detail['order_id'] = $order_id;
                    $Detail['is_active'] = 1;//激活
                    $Detail['card_status'] = 1; //已付款
                    Db::name('course_order_detail')->insert($Detail);
                    Db::name('user')->where(['user_id'=>$this->user['user_id']])->setDec('balance',$pay_money);
                    Db::name('course_card')->where(['id'=>$courseCard['id']])->setInc('sales_actual'); //销量+1
                    Db::name('course_order')->where(['order_id'=>$order_id])->update(['pay_status'=>20,'pay_time'=>time()]);
                    // 设置优惠券使用状态
                    UserCouponModel::setIsUse($data['coupon_id']);
                    BalanceLog::add(Scene::COURSE,[
                        'user_id'=>$this->user['user_id'],
                        'money'=>$Add['pay_price'],
                    ],['order_no'=>$Add['order_no']]);
                    Db::commit();
                    return $this->renderSuccess([],'下单成功');
                }catch (\Exception $exception){
                    Db::rollback();
                    return $this->renderError('下单失败');
                }
            }else{
//                $Add['pay_price'] = 0.01;
                $Add['is_active'] = 1;//激活
                $order_id = Db::name('course_order')->insertGetId($Add);
                $Detail['order_id'] = $order_id;
                $Detail['is_active'] = 1;//激活
                Db::name('course_order_detail')->insert($Detail);
                // 设置优惠券使用状态
                UserCouponModel::setIsUse($coupon_id);
                $payment = $this->createWxOrder($this->user['user_id'],$order_id,$Add['order_no'],$Add['pay_price'],OrderType::COURSE);
                return $this->renderSuccess(compact('payment'),'创建订单成功');
            }


        }else{
            return $this->renderError('请求异常');
        }
    }

    public function createWxOrder($user_id,$order_id,$order_no,$order_price,$order_type){
        return Payment::wechat($this->user,$order_id,$order_no,$order_price,$order_type);
    }

    /**
     * @title 课程卡订单列表
     * @author Qian
     * Time: 2023/2/28  0:09
     */
    public function OrderList(){
        $model = new CourseOrder();
        $list = $model->getList($this->user['user_id']);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * @title 购买视频课程
     * @author Qian
     * Time: 2023/4/7  9:18
     */
    public function VideoOrder(){
        if ($this->request->isPost()){
            if ($this->user['phone'] == ''){
                return $this->renderError('还未绑定手机号');
            }
            $data = $this->request->param();
            if (!isset($data['c_id']) || $data['c_id'] == ''){
                return $this->renderError('请选择购买的视频课程');
            }
            $coupon_id = isset($data['coupon_id'])?$data['coupon_id'] : 0;
            $service = new \app\common\service\Course();
            $video_order = $service->createOrder($data['c_id'],$this->user['user_id'],$coupon_id);
            // 设置优惠券使用状态

            UserCouponModel::setIsUse($coupon_id);
            $payment = $this->createWxOrder($this->user['user_id'],$video_order['order_id'],$video_order['out_trade_no'],$video_order['pay_price'],OrderType::VIDEO);
            return $this->renderSuccess(compact('payment'),'创建订单成功');
        }
    }

    public function getVideoCoupon(){
        $data = $this->request->param();
        if (!isset($data['c_id']) || $data['c_id'] == ''){
            return $this->renderError('请选择购买的视频课程');
        }
        $video = $detail = Course::detail($data['c_id']);
        if (!$video){
            return $this->renderError('视频课程不存在');
        }
        $coupon = UserCouponModel::getUserCouponList($this->user['user_id'],$video['price']);
        return $this->renderSuccess(compact('coupon'));
    }

    /**
     * @title 视频列表
     * @author Qian
     * Time: 2023/4/7  11:13
     */
    public function VideoList(){
        //该用户的视频列表
        $list = (new UserCourse())->getList(['user_id'=>$this->user['user_id']],10);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * @title 视频章节
     * @author Qian
     * Time: 2023/4/7  14:35
     */
    public function VideoPart(){
        $data = $this->request->param();
        $model = new UserCourse();
        $user_course_id = $data['user_course_id'];
        $user_course = UserCourse::get($user_course_id);
        if ($user_course['status'] == 2){
            return $this->renderError('该视频课程已失效');
        }
        $OrderPart = $model->getCoursePart($user_course_id,1);
        return $this->renderSuccess(compact('OrderPart'));
    }
}